package com.gwz.wxtime.openai.com.theokanning.openai;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;

import java.util.List;

/**
 * PSApi Feign配置
 *
 * @author junbing.gong
 * @date 2021/9/3 16:00
 */
@Slf4j
public class OPenAiConfig {


    @Value("${chatGpt.key}")
    private String token;

    private String[] tokens;

    private int index = 0;


    @Bean
    public OPenAiConfig.FeignInterceptor psApiRequestInterceptor() {
        return new FeignInterceptor();
    }

    public class FeignInterceptor implements RequestInterceptor {
        public FeignInterceptor() {
        }

        @Override
        public void apply(RequestTemplate requestTemplate) {
            if (ArrayUtil.isEmpty(tokens)) {
                tokens = token.split(",");
            }
            String token = tokens[index];
            index++;
            if (index >= tokens.length) index = 0;


            log.info("当前访问token:{}", token);
            requestTemplate.header(HttpHeaders.AUTHORIZATION, "Bearer " + token);
        }
    }
}
